package com.zhangx.study.demo.rpc.server;

import com.zhangx.study.demo.rpc.server.model.User;
import com.zhangx.study.demo.rpc.server.service.IUserService;
import com.zhangx.study.demo.rpc.server.service.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName RpcServer
 * @Description TODO
 * @Author zhangx
 * @Date 2020/10/12 8:18
 **/
@Slf4j
public class RpcServerV4 {

    private static boolean running = true;

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            while (running){
                Socket socket = serverSocket.accept();
                process(socket);
                socket.close();
            }
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void process(Socket socket){
        try {
            InputStream in = socket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(in);
//            获取参数
            String methodName = ois.readUTF();
            log.info(methodName);
            Class[] paramerTypes = (Class[]) ois.readObject();
            Object[] args = (Object[]) ois.readObject();
//            反射调用userService中指定的方法
            IUserService userService = new UserServiceImpl();
            Method method = userService.getClass().getMethod(methodName,paramerTypes);
            User user = (User) method.invoke(userService,args);
//            返回数据
            OutputStream out = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(out);
            dataOutputStream.writeInt(user.getAge());
            dataOutputStream.writeUTF(user.getName());
            dataOutputStream.flush();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
